package com.aode.music.view.fragment.mainfragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.aode.common.bean.request.Request;
import com.aode.common.bean.request.SearchData;
import com.aode.common.bean.response.Music;
import com.aode.music.R;
import com.aode.music.adapter.music.MusicAdapter;
import com.aode.music.databinding.FragmentMusicBinding;
import com.aode.music.viewmodel.MusicViewModel;
import com.aode.musicdetail.view.activity.MusicDetailActivity;
import com.aode.utils.main.ToastUtils;
import com.example.chat.view.activity.ChatActivity;

import java.util.ArrayList;

public class MusicFragment extends Fragment implements MusicAdapter.MusicInterface, SwipeRefreshLayout.OnRefreshListener {
    private FragmentMusicBinding musicBinding;
    private ArrayList<Music> musicArrayList = new ArrayList<>();
    private ArrayList<Music> headMusicArrayList = new ArrayList<>();
    private ArrayList<Music> footMusicArraylist = new ArrayList<>();
    private MusicViewModel musicViewModel;
    private RecyclerView recyclerView;
    private MusicAdapter musicAdapter;
    private static int num=0;
    private  static boolean flag = false;
    private static int total;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        musicBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_music,container,false);
        musicViewModel = ViewModelProviders.of(this).get(MusicViewModel.class);
        num = 1;
        flag = false;
        showPopularMusic();
        initListener();
        return  musicBinding.getRoot();
    }

    private void showPopularMusic() {
        SearchData searchData = new SearchData();
        searchData.setPageNum(num);
        searchData.setPageSize(10);
        musicViewModel.getMusic(searchData);

    }

    private void LoadMoreMusic() {
        musicAdapter = new MusicAdapter(getContext(),musicArrayList,this);
        recyclerView = musicBinding.recyclerview;
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(musicAdapter);
        if(flag){
            Log.e("TAGAddFooterItem",flag+"");
            Log.e("TAG FooterItemMusicList",musicArrayList.size()+"");
            Log.e("TAG FooterItem",footMusicArraylist.size()+"");
            musicAdapter.AddFooterItem(footMusicArraylist);
            if(footMusicArraylist.size()>0&&!footMusicArraylist.isEmpty()){
                footMusicArraylist.clear();
            }

        }else{
            musicAdapter.AddHeaderItem(headMusicArrayList);
            Log.e("TAGAddHeaderItem",flag+"");
            Log.e("TAG HeaderItemMusicList",musicArrayList.size()+"");
            Log.e("TAG HeaderItem",headMusicArrayList.size()+"");
            if(headMusicArrayList.size()>0&&!headMusicArrayList.isEmpty()){
                headMusicArrayList.clear();
            }
        }
    }

    private void initListener() {
        initMusicDataListener();
        initPullRefresh();
        initLoadMoreListener();
    }

    private void initMusicDataListener() {
        musicViewModel.getMusicLiveData().observe(getViewLifecycleOwner(), pageResult -> {
            if(pageResult.getCode().equals("0")){
                total = pageResult.getData().getPages();
                if(flag){
                    footMusicArraylist = new ArrayList<>();
                    footMusicArraylist = (ArrayList<Music>) pageResult.getData().getRecords();
                }else {
                    headMusicArrayList =new ArrayList<>();
                    headMusicArrayList = (ArrayList<Music>) pageResult.getData().getRecords();
                }
                LoadMoreMusic();
            }else{
                ToastUtils.show(getContext(),pageResult.getMsg());
            }

        });
    }

    private void initPullRefresh() {
        musicBinding.swiperefresh.setOnRefreshListener(this);
    }

    private void initLoadMoreListener() {
        musicBinding.recyclerview.setOnScrollListener(new RecyclerView.OnScrollListener() {
            int lastVisibleItem;
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(newState==RecyclerView.SCROLL_STATE_IDLE&&lastVisibleItem+1==musicAdapter.getItemCount()){
                    flag = true;
                    num++;
                    if(num>total){
                        ToastUtils.show(getContext(),"没有更多数据");
                    }else{
                        showPopularMusic();
                    }
                }

            }
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                //最后一个可见的ITEM
                lastVisibleItem=layoutManager.findLastVisibleItemPosition();
            }
        });
    }


    @Override
    public void onRefresh() {
        flag = false;
        num++;
        if(num>total){
            ToastUtils.show(getContext(),"没有更多数据了");
        }else{
            showPopularMusic();
        }
        musicBinding.swiperefresh.setRefreshing(false);
    }

    @Override
    public void onItemClick(Music music) {
        Log.e("TAGMusic",music.getMusicId()+"");
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putParcelable("music",music);
        intent.putExtras(bundle);
        intent.setClass(getActivity(), MusicDetailActivity.class);
        startActivityForResult(intent, Request.MUSIC_TO_MUSIC_DETAIL);
    }
}
